package loader.parser;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;

import loader.parser.adapter.Adapter4MeiTuan;
import loader.parser.adapter.SiteAdapter;
import loader.persister.CityPersister;
import loader.persister.Persister;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Parser {

	private Persister persister;

	public Parser() {
	}

	public Parser(Persister persister) {
		this.setPersister(persister);
	}

	public static void main(String[] args) {

		SiteAdapter a = new Adapter4MeiTuan();
		Persister p = new CityPersister(a);
		p.clear();
		
		Parser d = new Parser(p);
		try {
			d.parse(new URL(a.getCitiesUrl()));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		try {
			p.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void parse(InputStream in) {
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(in);
			parserDocument(document);
		} catch (DocumentException e) {
			System.out.println(e.getMessage());
		}
	}

	public void parse(URL url) {
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(url);
			parserDocument(document);
		} catch (DocumentException e) {
			System.out.println(e.getMessage());
		}
	}

	public void parse(String fileName) {
		File inputXml = new File(fileName);
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(inputXml);
			parserDocument(document);
		} catch (DocumentException e) {
			System.out.println(e.getMessage());
		}
	}

	private void parserDocument(Document document) {
		Element deals = (Element) document.getRootElement().elements().get(0);
		deepIn(deals);
	}

	private void deepIn(Element ele) {
		@SuppressWarnings("unchecked")
		List<Element> elements = ele.elements();
		this.persister.detectNewObject(ele);
		if (elements.size() == 0) {
			this.persister.addProperty(ele);
		} else {
			for (Element e : elements) {
				deepIn(e);
			}
		}
	}

	public void setPersister(Persister persister) {
		this.persister = persister;
	}

	public Persister getPersister() {
		return persister;
	}
}